#pragma once

#include <iostream>
#include <string>
#include <cstdio>
#include <stdarg.h>
#include <sys/types.h>
#include <unistd.h>

using namespace std;

#define DEBUG   0
#define NORMAL  1
#define WARNING 2
#define ERROR   3
#define FATAL   4

const char* levelToString(int level)
{
    switch (level)
    {
    case DEBUG:
        return "DEBUG";
    case NORMAL:
        return "NORMAL";
    case WARNING:
        return "WARNNING";
    case ERROR:
        return "ERROR";
    case FATAL:
        return "FATAL";
    default:
        return nullptr;
    }
}

void logMessage(int level, const char* format, ...)
{
    // [日志等级] [时间戳/时间] [pid] [messge]
    // [WARNING] [2023-05-11 18:09:08] [123] [创建socket失败]

    char logPrefix[1024];
    snprintf(logPrefix, sizeof logPrefix, "[%s][%ld][%d]", levelToString(level), (long int)time(nullptr), getpid());
    char logContent[1024];
    va_list arg;
    va_start(arg, format);//让arg指向可变参数的起始位置
    vsnprintf(logContent, sizeof logContent, format, arg);//将format的内容输出到content中

    //由于服务器进程已脱离终端 日志内容需要输出到文件中
    FILE* fp = fopen("./log.txt", "a+");
    if (fp)
    {
        fprintf(fp, "%s [%s]\n", logPrefix, logContent);
        fclose(fp);
    }
}